#
# LuckyBot4, a python IRC bot
# (c) Copyright 2008 by Lucas van Dijk
# http://www.return1.net
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA
#
# $Id: console.py 55 2009-03-26 23:32:19Z luckyluke56 $
#

import luckybot.views.base
from luckybot.luckynet.connection.glib import GlibConnection
import socket
import gobject
from luckybot.bot import irc

class Server(object):
	def __init__(self, server_config, view):
		self.server_config = server_config
		self.view = view

	def open_connection(self, config):
		"""
			Opens the connection to a specified IRC Server

			If called without paramaters, the hostname and port is read
			from the settings file.

			@type config: tuple
			@param config: Tuple containing all server config in following order:
				hostname, port, nickname, password, channels
		"""

		host, port, nickname, password, channels, send_as_notice = config

		connection = GlibConnection(socket.AF_INET, socket.SOCK_STREAM)
		protocol = irc.Client(self.view.bot, nickname, password, channels.split(','), send_as_notice, self.view.bot.settings.getboolean('Bot', 'invisible'))
		protocol.connect('irc-event', self.view.bot.on_message)
		protocol.connect('data-sent', self.on_data_sent)
		protocol.connect('data-received', self.on_data_received)
		protocol.connect('closed', self.on_client_close)

		connection.set_protocol(protocol)
		connection.open((host, port))
		connection.setblocking(0)

		self.client = protocol

	def connect_to_server(self):
		"""
			Connect to the server
		"""

		if (not 'nickname' in self.server_config or
				not 'hostname' in self.server_config):
			raise ValueError, ('Incomplete configuration, need at least' +
				' hostname and nickname')

		try:
			port = int(self.server_config['port'])
		except:
			port = 6667

		channels = self.server_config['channels'] if 'channels' in self.server_config else ''
		password = self.server_config['password'] if 'password' in self.server_config else ''
		send_as_notice = True if 'send_as_notice' in self.server_config and self.server_config['send_as_notice'].lower() == 'true' else False

		config = (self.server_config['hostname'], port, self.server_config['nickname'],
			password, channels, send_as_notice)

		self.open_connection(config)
		self.connected = True

	def on_data_received(self, sender, data):
		"""
			Called when data arrives
		"""

		print "[%s:%d]" % (self.client.connection.addr[0], sender.connection.addr[1]), "<<< ", data.strip()

	def on_data_sent(self, sender, data):
		"""
			Called when data is sent, sends the data to our view
		"""

		print "[%s:%d]" % (self.client.connection.addr[0], sender.connection.addr[1]), ">>> ", data.strip()

	def on_client_close(self, sender):
		"""
			Called when the socket is closed
		"""

		self.connected = False
		del self.client

		self.view.on_close()

class ConsoleView(luckybot.views.base.BaseView):
	"""
		This view displays all in and out coming data in console
	"""

	def __init__(self):
		self.loop = gobject.MainLoop()
		self.connections = 0

	def error(self, data):
		print "ERROR: ", data

	def on_close(self):
		self.connections -= 1

		if self.connections == 0:
			self.loop.quit()

	def start(self):

		servers = self.bot.get_servers()

		for server_config in servers:
			connection = Server(server_config, self)
			connection.connect_to_server()

		self.loop.run()

